package cn.tedu.tmall.passport.service.impl;

import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import cn.tedu.tmall.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.tmall.common.pojo.po.UserStatePO;
import cn.tedu.tmall.passport.dao.cache.IUserCacheRepository;
import cn.tedu.tmall.passport.dao.persist.repository.IUserRepository;
import cn.tedu.tmall.passport.pojo.param.UserLoginInfoParam;
import cn.tedu.tmall.passport.pojo.vo.UserLoginInfoVO;
import cn.tedu.tmall.passport.pojo.vo.UserLoginResultVO;
import cn.tedu.tmall.passport.service.IUserService;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserServiceImpl implements IUserService {

    @Value("${tmall.jwt.secret-key}")
    private String secretKey;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IUserRepository userRepository;
    @Autowired
    private IUserCacheRepository userCacheRepository;

    @Override
    public UserLoginResultVO login(UserLoginInfoParam userLoginInfoParam, String remoteAddr, String userAgent) {
        String username = userLoginInfoParam.getUsername();
        UserLoginInfoVO loginInfo = userRepository.getLoginInfoByUsername(username);
        if (loginInfo == null) {
            String message = "登录失败，用户名或密码错误！";
            throw new ServiceException(ServiceCode.ERROR_UNAUTHORIZED, message);
        }

        if (loginInfo.getEnable() != 1) {
            String message = "登录失败，此账号已经被禁用！";
            throw new ServiceException(ServiceCode.ERROR_UNAUTHORIZED_DISABLED, message);
        }

        String password = userLoginInfoParam.getPassword();
        // if (!loginInfo.getPassword().equals(password)) {
        if (!passwordEncoder.matches(password, loginInfo.getPassword())) {
            String message = "登录失败，用户名或密码错误！";
            throw new ServiceException(ServiceCode.ERROR_UNAUTHORIZED, message);
        }

        // TODO 处理登录日志相关：向登录日志表中插入数据，修改用户表中冗余存储的登录数据

        // 确定当事人
        CurrentPrincipal principal = new CurrentPrincipal();
        principal.setId(loginInfo.getId());
        principal.setUsername(loginInfo.getUsername());

        // 确定权限列表
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions = loginInfo.getPermissions();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }

        // 将权限列表和用户状态写入到Redis中
        String authoritiesJsonString = JSON.toJSONString(authorities);
        UserStatePO userStatePO = new UserStatePO();
        userStatePO.setEnable(loginInfo.getEnable());
        userStatePO.setAuthoritiesJsonString(authoritiesJsonString);
        userCacheRepository.saveUserState(loginInfo.getId(), userStatePO);

        // 向SecurityContext中存入Authentication
        // Authentication authentication = new UsernamePasswordAuthenticationToken(
        //        principal, null, authorities);
        // SecurityContext securityContext = SecurityContextHolder.getContext();
        // securityContext.setAuthentication(authentication);

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", loginInfo.getId());
        claims.put("username", loginInfo.getUsername());
        claims.put("remote_addr", remoteAddr);
        claims.put("user_agent", userAgent);

        String jwt = Jwts.builder()
                // Header
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                // Payload
                .setClaims(claims)
                // Verify Signature
                .signWith(SignatureAlgorithm.HS256, secretKey)
                // 完成
                .compact();

        UserLoginResultVO loginResult = new UserLoginResultVO();
        loginResult.setId(loginInfo.getId());
        loginResult.setUsername(loginInfo.getUsername());
        loginResult.setAvatar(loginInfo.getAvatar());
        loginResult.setToken(jwt);
        loginResult.setAuthorities(permissions);
        return loginResult;
    }

    @Override
    public void logout(CurrentPrincipal currentPrincipal) {
        Long id = currentPrincipal.getId();
        userCacheRepository.deleteUserState(id);
    }

}
